import 'dart:convert';
import 'package:cbec_app/components/base/base_ctr.dart';
import 'package:cbec_app/components/http/network.dart';
import 'package:cbec_app/components/popup/pre_sale_ruler_popop.dart';
import 'package:cbec_app/components/popup/select_specifications_popup.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/EventMgr.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:cbec_app/utils/logger.dart';
import 'package:flutter/material.dart';
import 'package:fluwx/fluwx.dart';
import 'package:get/get.dart';

import '../../../components/app_conifg.dart';

///商品详情控制器
class GoodsDetailController extends BaseController {
  var isCollect = false;
  var collectIcon = 'collect.png';

  ///商品id
  String goodsId = '';

  ///规格列表
  List skus = [];

  ///显示的sku列表
  List showSkus = [];

  ///已选商品数量
  int selectedGoodsNum = 1;

  /// 是否已经点击过规格弹窗，用于需不需要再次弹窗
  bool isDidSureTap = false;

  ///已选商品规格数量
  int selectedSpecNum = 1;

  ///已选商品规格索引
  int selectedIndex = 0;

  ///商品详情
  Map<String, dynamic> detail = {};

  ///商品价格信息
  Map<String, dynamic> priceInfo = {};

  ///商品主图、主视频
  List goodsImages = [];

  ///商品富文本详情
  String goodsRichDetail = '';

  ///收获地址
  String address = '';

  ///购物车商品数量
  int carGoodsNum = 0;

  ///服务详情列表
  List serviceList = [];

  ///地址id
  String addressId = '';

  ///选规格的商品信息
  Map<String, dynamic> goodsInfo = {};

  ///到手价
  String deliveryPrice = '0';

  ///是否自动跳转
  bool isAutoJump = false;

  /// 是否能展示规格弹窗
  bool isCanShowSpecifications = false;

  ///评论分页
  ///每页数量
  int commentPageSize = 10;

  ///当前页
  int commentPageNum = 1;

  ///评论列表
  List commentList = [];

  // 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
  // 由商品详情字段判断，不再从其他入口获取. 这句很重要
  int goodsType = 0;

  ///秒杀信息
  Map<String, dynamic> seckillInfo = {};

  ///拼团信息
  Map<String, dynamic> bookInfo = {};

  ///特价信息
  Map<String, dynamic> specialInfo = {};

  ///砍价信息
  Map<String, dynamic> haggleInfo = {};

  ///预售信息
  Map<String, dynamic> preSaleInfo = {};

  ///新人专区
  Map<String, dynamic> newUserInfo = {};

  ///优惠信息
  Map<String, dynamic> preferentialInfo = {};

  ///优惠标签
  List tags = [];

  ///判断是否以及加入购物车
  bool isAddShopCard = false;

  //  消费者告知书
  Map<String, dynamic> consumerNotice = {};

  List specPriceList = [];

  /// 秒杀、拼团、预售、砍价，只要商品参加了这四个活动，就没有领券按钮
  bool isShowCouponBtn = true;

  /// 是否使用运费模板 0-使用运费模板 1-使用统一邮费
  int freightType = 0;

  @override
  void onInit() async {
    super.onInit();
    goodsId = Get.arguments['id']!;
    await getGoodsDetail();
    await getCarList();
    await getCarGoodsNum();
    await getCommentList();
    calcDeliveryPrice();
    await getPreferentialConfig();
    print('isShowCouponBtn ======== $isShowCouponBtn');
    update();

    ///监听选择地址
    EventMgr.on(EventType.selectAddress, (data) {
      addressId = data['id'];
      address = '${data['provinceName']} ${data['cityName']} ${data['districtName']} ${data['receiveAddress']}';
      update();
    });
  }

  @override
  void onClose() {
    super.onClose();
    EventMgr.off(EventType.selectAddress);
  }

  ///获取购物车商品数量
  Future<void> getCarGoodsNum() async {
    Network.getCarGoodsNum().then((value) {
      carGoodsNum = value;
      update();
    });
  }

  ///获取评论列表
  Future<void> getCommentList() async {
    Map<String, dynamic> params = {};
    params['sid'] = AppData.sid;
    params['id'] = detail['commodityId'];
    params['pageNum'] = commentPageNum;
    params['pageSize'] = commentPageSize;
    if (detail['commodityId'] == null) {
      return;
    }
    Network.getGoodsCommentList(detail['commodityId'], params).then((value) {
      commentList = value['pageInfo']['list'];
      update();
    });
  }

  List cardList = [];

  ///获取购物车的所有商品的
  Future getCarList() async {
    return Network.getCarList().then((value) {
      List goodsGroupList = value['goodsGroup'];
      for (int i = 0; i < goodsGroupList.length; i++) {
        List goodsList = goodsGroupList[i]['goodsList'];
        for (int j = 0; j < goodsList.length; j++) {
          cardList.add(goodsList[j]);
        }
      }
    }).catchError((onError) {});
  }

  void canJoinCart(Function(bool) callback) {
    bool isCan = false;
    isAutoJump = false;

    if (isCanShowSpecifications) {
      if (!isDidSureTap) {
        print('isCanShowSpecifications ===== $isCanShowSpecifications');
        showSelectSpecificationsPopup(
          mainImg: isCanShowSpecifications ? detail['imageList'].first : null,
          goodsInfo: detail,
          goodsType: goodsType,
          goodsNum: selectedGoodsNum,
          selectedIndex: selectedIndex,
          onConfirm: (specIndex, goodsNum, groupIndex) {
            joinSku(specIndex, goodsNum);
            isCan = true; // 在确认时设置 isCan
            callback(isCan); // 调用回调并传递结果
          },
          onSelectSku: (id) {
            onSelectSku(id);
          },
          specValue: '${detail['spuSpecJsonBody']}',
        );
      } else {
        isCan = true; // 如果已经确认规格
        callback(isCan); // 调用回调并传递结果
      }
    } else {
      isCan = true; // 如果没有可选规格，默认可以加入
      callback(isCan); // 调用回调并传递结果
    }
  }

  ///加入购物车
  void addCar() {
    if (isAddShopCard) {
      Tools.showToast('该商品已经在购物车了');
      return;
    }
    for (int i = 0; i < cardList.length; i++) {
      if (cardList[i]['goodsId'] == detail['commodityId']) {
        Tools.showToast("购物车以存在该商品");
        return;
      }
    }

    canJoinCart((canAdd) {
      Map<String, dynamic> params = {};
      params['buyNum'] = selectedGoodsNum;
      params['goodsId'] = detail['commodityId'];
      params['isSelect'] = 1;
      params['isSend'] = 0;
      params['sid'] = AppData.sid;
      params['specNum'] = priceInfo['specNum'];
      Network.addCar(params).then((value) {
        if (value) {
          Tools.showToast('添加成功');
          isAddShopCard = true;
          carGoodsNum += 1;
          EventMgr.send(EventType.refreshCar);
          resetSelected();
          update();
        }
      });
    });
  }

  ///收藏、取消收藏
  toggleCollect() {
    isCollect = !isCollect;
    if (isCollect) {
      collectGoods();
    } else {
      cancelCollect();
    }
  }

  ///收藏商品
  void collectGoods() {
    Network.collect(goodsId).then((value) {
      if (value) {
        Tools.showToast('收藏成功');
        collectIcon = 'collect_selected.png';
        update();
      } else {
        Tools.showToast('收藏失败');
      }
    });
  }

  ///取消收藏
  void cancelCollect() {
    Network.deleteCollect(goodsId).then((value) {
      if (value) {
        Tools.showToast('取消收藏');
        collectIcon = 'collect.png';
        update();
      } else {
        Tools.showToast('取消收藏失败');
      }
    });
  }

  ///获取商品详情
  Future getGoodsDetail() async {
    Map<String, dynamic> params = {};
    params['sid'] = AppData.sid;
    params['type'] = 0;
    if (goodsId.isEmpty) {
      Tools.showToast('无商品id');
      Tools.hideLoading();
      await Future.delayed(const Duration(seconds: 1));
      Get.back();
    } else {
      Tools.showLoading();
      return Network.getGoodsDetail(goodsId, params).then((value) {
        Tools.hideLoading();

        print('详情数据 $value');

        detail = value;
        isCollect = value['isCollection'] == 0 ? false : true;
        collectIcon = isCollect ? 'collect_selected.png' : 'collect.png';
        goodsImages = value['imageList'];
        skus = value['skuBase']?['skus'] ?? [];
        showSkus = skus.length >= 5 ? skus.sublist(0, 4) : skus;
        goodsRichDetail = value['content'];
        address = value['addressInfo'] ?? '';
        serviceList = value['serviceList'];
        addressId = value['addressId'] ?? '';
        priceInfo = value['specPriceList'][selectedIndex];
        goodsInfo['imgUrl'] = goodsImages[0];
        goodsInfo['price'] = priceInfo['price'];
        goodsInfo['priceMarket'] = priceInfo['priceMarket'];
        tags = value['activityTag'] ?? [];

        consumerNotice = value['consumerNotice'];

        specPriceList = value['specPriceList'];

        canShowSpecifications();

        logger.i('consumerNotice $consumerNotice');

        setGoodsType();

        update();
      }).catchError((onError) async {
        Tools.hideLoading();
        await Future.delayed(const Duration(seconds: 1));
        Get.back();
      });
    }
  }

  ///设置商品类型
  void setGoodsType() {
    // 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
    goodsType = 0;

    isShowCouponBtn = true;

    //特价商品
    if (detail['specialInfo'] != null) {
      goodsType = 2;
      specialInfo = detail['specialInfo'];
      isShowCouponBtn = true;
    }

    //秒杀商品
    if (detail['seckillInfo'] != null) {
      goodsType = 3;
      seckillInfo = detail['seckillInfo'];
      isShowCouponBtn = false;
    }
    //拼团商品
    if (detail['bookInfo'] != null) {
      goodsType = 4;
      bookInfo = detail['bookInfo'];
      isShowCouponBtn = false;
    }

    //预售商品
    if (detail['preSaleInfo'] != null) {
      goodsType = 5;
      preSaleInfo = detail['preSaleInfo'];
      print('preSaleInfo ===== $preSaleInfo}');
      isShowCouponBtn = false;
    }

    //卡券
    if (detail['commodityForm'] != null && detail['commodityForm'] == 2) {
      goodsType = 6;
    }

    // TODO 充值订单

    //砍价商品
    if (detail['haggleInfo'] != null) {
      goodsType = 8;
      haggleInfo = detail['haggleInfo'];
      isShowCouponBtn = false;
    }

    //新人专区
    if (detail['newUserInfo'] != null) {
      goodsType = 9;
      newUserInfo = detail['newUserInfo'];
      isShowCouponBtn = false;
    }
  }

  ///拼接规格参数
  void joinSku(int specIndex, int goodsNum) {
    selectedIndex = specIndex;
    priceInfo = detail['specPriceList'][specIndex];
    selectedSpecNum = priceInfo['specNum'];
    selectedGoodsNum = goodsNum;
    isDidSureTap = true;
    calcDeliveryPrice();
    update();
    if (isAutoJump) {
      jumpFillOrder();
    }
  }

  ///校验地址
  bool checkAddress() {
    if (!Tools.checkEmpty(address)) {
      Tools.showToast('请选择地址');
      return false;
    }
    return true;
  }

  ///跳转填写订单页
  void jumpFillOrder() {
    if (!isCanPurchase()) {
      Tools.showToast('活动已结束');
      return;
    }
    isAutoJump = true;
    if (isCanShowSpecifications) {
      if (!isDidSureTap) {
        showSelectSpecificationsPopup(
          mainImg: isCanShowSpecifications ? detail['imageList'].first : null,
          goodsInfo: detail,
          goodsType: goodsType,
          goodsNum: selectedGoodsNum,
          selectedIndex: selectedIndex,
          onConfirm: (specIndex, goodsNum, groupIndex) {
            joinSku(specIndex, goodsNum);
          },
          onSelectSku: (id) {
            onSelectSku(id);
          },
          specValue: '${detail['spuSpecJsonBody']}',
        );
        return;
      }
    }
// 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
    switch (goodsType) {
      case 0:
        normalPreOrder();
        break;
      case 2:
        bool isPreNotice = specialInfo['status'] == 3;
        isPreNotice ? normalPreOrder() : specialPreOrder();
        break;
      case 3:
        bool isPreNotice = seckillInfo['status'] == 3;
        isPreNotice ? normalPreOrder() : seckillPreOrder();
        break;
      case 4:
        bool isPreNotice = bookInfo['status'] == 3;
        isPreNotice ? normalPreOrder() : createTeamWork();
        break;
      case 5:
        bool isPreNotice = preSaleInfo['status'] == 3;
        isPreNotice ? normalPreOrder() : preSalePreOrder();
        break;
      case 6:
        cardCouponOrder();
        break;
      case 7:
        break;
      case 8:
        normalPreOrder();
        break;
      case 9:
        newUserOrder();
        break;
    }
  }

  ///普通商品预下单
  void normalPreOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 0;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  void newUserOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 9;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['activityId'] = newUserInfo['newUserActivityId'];
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///特价商品预下单
  void specialPreOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 2;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['activityId'] = specialInfo['seckillActivityId'];
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///秒杀商品预下单
  void seckillPreOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 3;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['activityId'] = seckillInfo['seckillActivityId'];
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///拼团预下单
  void teamWorkPreOrder(Map<String, dynamic> info) {
    Map<String, dynamic> params = {};
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['sid'] = AppData.sid;
    params['activityId'] = bookInfo['bookActivityId'];
    params['bookNum'] = info['peopleNumber'];
    params['type'] = 4;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///预售商品下单
  void preSalePreOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 5;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['activityId'] = preSaleInfo['presaleActivityId'];
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///卡券订单下单
  void cardCouponOrder() {
    Map<String, dynamic> params = {};
    params['type'] = 6;
    params['client'] = GetPlatform.isIOS ? AppConfig.clientIos : AppConfig.clientAndroid;
    params['goodsList'] = getPlaceOrderGoodsList();
    params['activityId'] = '';
    params['sid'] = AppData.sid;
    params['addressId'] = addressId;
    resetSelected();
    Get.toNamed(Routes.fillOrder, arguments: params);
  }

  ///重置选中
  void resetSelected() {
    selectedGoodsNum = 1;
    isDidSureTap = false;
    update();
  }

  ///计算到手价
  void calcDeliveryPrice() {
    switch (goodsType) {
      // 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
      case 2: //特价商品
        deliveryPrice = (specialInfo['priceSpecial'] * selectedGoodsNum as double).toStringAsFixed(2);
      case 3: //秒杀商品
        deliveryPrice = (seckillInfo['priceSeckill'] as double).toStringAsFixed(2);
        break;
      case 0: //普通商品
      default:
        deliveryPrice = (priceInfo['price'] * selectedGoodsNum as double).toStringAsFixed(2);
    }
  }

  ///判断是否能够正常购买
  bool isCanPurchase() {
    switch (goodsType) {
      // 0-普通订单 2-特价订单 3-秒杀订单 4-拼团订单 5-预售订单 6-卡券订单 7-充值订单 8-砍价订单 9-新人好礼订单
      case 2: //特价时间是否已结束
        int time = specialInfo['endTime'] * 1000 - DateTime.now().millisecondsSinceEpoch;
        if (time > 0) {
          return true;
        } else {
          return false;
        }
      case 3: //秒杀时间是否已结束
        int time = seckillInfo['endTime'] * 1000 - DateTime.now().millisecondsSinceEpoch;
        if (time > 0) {
          return true;
        } else {
          return false;
        }
      case 4: //拼团时间是否结束
        int time = bookInfo['endTime'] * 1000 - DateTime.now().millisecondsSinceEpoch;
        if (time > 0) {
          return true;
        } else {
          return false;
        }
      case 5: //预售时间是否结束
        int time = preSaleInfo['endTime'] * 1000 - DateTime.now().millisecondsSinceEpoch;
        if (time > 0) {
          return true;
        } else {
          return false;
        }
      case 8: //砍价时间是否结束
        int time = haggleInfo['endTime'] * 1000 - DateTime.now().millisecondsSinceEpoch;
        if (time > 0) {
          return true;
        } else {
          return false;
        }
      case 0:
      default:
        return true;
    }
  }

  ///下单商品列表
  List<Map<String, dynamic>> getPlaceOrderGoodsList() {
    List<Map<String, dynamic>> arr = [];
    Map<String, dynamic> info = {};
    info['buyNum'] = selectedGoodsNum;
    info['goodsId'] = detail['commodityId'];
    info['isSelect'] = 1;
    info['isSend'] = 0;
    info['specNum'] = selectedSpecNum;
    arr.add(info);
    return arr;
  }

  ///选择规格
  void onSelectSku(String id) async {
    goodsId = id;
    await getGoodsDetail();
    EventMgr.send(EventType.refreshSkuPopup, goodsType);
    EventMgr.send(EventType.refreshSkuPopup, detail);
    update();
  }

  void canShowSpecifications() {
    isCanShowSpecifications = (skus.isNotEmpty || specPriceList.isNotEmpty);
  }

  ///跳转砍价详情
  void jumpBargainingDetail() {
    if (isCanShowSpecifications) {
      showSelectSpecificationsPopup(
        mainImg: isCanShowSpecifications ? detail['imageList'].first : null,
        goodsInfo: detail,
        goodsNum: selectedGoodsNum,
        goodsType: goodsType,
        selectedIndex: selectedIndex,
        isShowGroup: false,
        selectedGroupIndex: 0,
        onSelectSku: (id) {
          onSelectSku(id);
        },
        onConfirm: (specIndex, goodsNum, groupIndex) {
          Get.toNamed('${Routes.bargainingDetail}/?goodsId=$goodsId&activityId=${haggleInfo['haggleActivityId']}&goodsList=${json.encode(getPlaceOrderGoodsList())}');
        },
      );
    } else {
      Get.toNamed('${Routes.bargainingDetail}/?goodsId=$goodsId&activityId=${haggleInfo['haggleActivityId']}&goodsList=${json.encode(getPlaceOrderGoodsList())}');
    }
  }

  ///发起拼团
  void createTeamWork() {
    print('isCanShowSpecifications ===== $isCanShowSpecifications');
    showSelectSpecificationsPopup(
      mainImg: isCanShowSpecifications ? detail['imageList'].first : null,
      goodsInfo: detail,
      goodsNum: selectedGoodsNum,
      goodsType: goodsType,
      selectedIndex: selectedIndex,
      isShowGroup: true,
      selectedGroupIndex: 0,
      onSelectSku: (id) {
        onSelectSku(id);
      },
      onConfirm: (specIndex, goodsNum, groupIndex) {
        Map<String, dynamic> info = bookInfo['priceList'][groupIndex];
        teamWorkPreOrder(info);
      },
    );
  }

  ///获取优惠配置
  Future getPreferentialConfig() {
    Map<String, dynamic> params = {};
    params['commodityId'] = goodsId;
    params['sid'] = AppData.sid;
    params['payNum'] = priceInfo['specNum'];
    params['price'] = priceInfo['price'];
    params['type'] = goodsType;
    return Network.goodsDetailActivity(params).then((value) {
      print('优惠信息====== $value');

      preferentialInfo = value;
      update();
    });
  }

  ///领取优惠券
  void receiveCoupon(String couponId) async {
    await Network.receiveCoupon(couponId);
    Tools.showToast('领取成功');
    await getPreferentialConfig();
    EventMgr.send(EventType.refreshDiscountPopup, preferentialInfo);
    update();
  }

  ///领取红包
  void receiveRedPack(String redPacketId) async {
    await Network.receiveRedPack(redPacketId);
    Tools.showToast('领取成功');
    await getPreferentialConfig();
    EventMgr.send(EventType.refreshDiscountPopup, preferentialInfo);
    update();
  }

  // @override
  // void onPageRefresh() async {
  //   super.onPageRefresh();
  //   await getGoodsDetail();
  //   update();
  //   baseRefreshCtr.refreshCompleted(resetFooterState: true);
  // }

  /// 预售规则弹窗
  showPreSaleRulerPopop() {
    showModalBottomSheet(
        context: Get.context!,
        builder: (content) {
          return PreSaleRulerPopop(descriptTxt: preSaleInfo['ruleContent']);
        });
  }

  Fluwx fluwx = Fluwx();
  // 分享小程序卡片
  void shareMiniProgram(String id, String imgUrl) async {
    if (GetPlatform.isIOS || GetPlatform.isAndroid) {
      bool isInstall = await fluwx.isWeChatInstalled;
      if (!isInstall) {
        Tools.showToast('请先安装微信');
        return;
      }
      // ## 1-商品详情， /pages/guide/index?type=1&data={sid:'店铺ID',id:'商品ID',uid:'用户ID'}
      final data = {'sid': AppData.sid, 'id': id, 'uid': AppData.uid};

      logger.i('data ==== $data  $imgUrl');

      // JSON 序列化和 URL 编码
      String jsonData = jsonEncode(data);

      var model = WeChatShareMiniProgramModel(
        userName: "gh_ac4763917949", //小程序的原始id,如 gh_d43f693ca31f
        webPageUrl: 'https://mv2.bd-ego.com/', //兼容老版本小程序的网页连接
        miniProgramType: WXMiniProgramType.release, //小程序类型，测试版本小程序
        path: "/pages/guide/index?type=1&data=$jsonData", //小程序的页面路径支持带?xx=121参数
        title: detail['commodityName'] ?? '', //分享的标题
        description: "", //分享的说明文本
        thumbnail: imgUrl.contains('http') ? WeChatImage.network(imgUrl) : WeChatImage.asset(imgUrl), // thumbData: imgUrl, // 分享的图片
      );

      print(model.toString());
      fluwx.share(model);
    }
  }
}
